package org.jeecg.modules.thirdpartyapi.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.ThirdPartyApi;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.thirdpartyapi.dto.AuthUserInfoDto;
import org.jeecg.modules.dzswj.DESUtil;
import org.jeecg.modules.dzswj.GuangdongSfjrApiService;
import org.jeecg.modules.dzswj.vo.request.SmzyhdlReqVo;
import org.jeecg.modules.dzswj.vo.response.DzswjBaseResponse;
import org.jeecg.modules.dzswj.vo.response.PzjgxxVo;
import org.jeecg.modules.dzswj.vo.response.SmzdlResponseVo;
import org.jeecg.modules.dzswj.vo.response.nsrxxcx.Nsrjbxx;
import org.jeecg.modules.dzswj.vo.response.nsrxxcx.NsrxxCxResponseVo;
import org.jeecg.modules.fk.entity.DjOrg;
import org.jeecg.modules.fk.service.IDjOrgService;
import org.jeecg.modules.front.vo.AuthReqVo;
import org.jeecg.modules.qyxx.entity.DjNsrxxPO;
import org.jeecg.modules.qyxx.enumdemo.RedisKeyConstant;
import org.jeecg.modules.qyxx.service.IDjNsrxxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author chensherun on 2022/3/9.
 * @version 1.0
 */
@Api(value = "用户授权（外部接口）", tags = "用户授权(外部接口)")
@Slf4j
@RestController
@RequestMapping("/thirdpart/api/auth")
public class AuthApiController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private GuangdongSfjrApiService sfjrApiService;

    @Autowired
    private IDjNsrxxService djNsrxxService;

    @Autowired
    private IDjOrgService djOrgService;

    @ThirdPartyApi(responseZip = true)
    @ApiOperation(value = "电局授权")
    @PostMapping("/smrz")
    public Result<?> auth(@RequestBody AuthReqVo authVo) {
        String fullKey = RedisKeyConstant.AUTH_USER_KEY + authVo.getKey();
        String dataStr = redisUtil.getString(fullKey);
        if (StringUtils.isBlank(dataStr)) {
            return Result.noauth("登录信息已失效");
        }
        AuthUserInfoDto authUserInfoDto = JSONObject.parseObject(dataStr, AuthUserInfoDto.class);
        if (authUserInfoDto == null || StringUtils.isBlank(authUserInfoDto.getMobilePhone())) {
            log.error("从redis获取的信息有误，fullKey:{}, value:{}", fullKey, dataStr);
            return Result.noauth("登录信息已失效");
        }
        redisUtil.setString(fullKey, dataStr, RedisKeyConstant.AUTH_USER_KEY_EXPIRE);

        //客户列表
        DjOrg djOrg = djOrgService.getByNsrsbhOrShxydm(authVo.getNsrsbh());
        if (djOrg != null && djOrg.getIsAuth() == 1 && StringUtils.isNotBlank(djOrg.getRealYhm())) {
            return Result.error("该企业已经授权！");
        }
        String mobile = authUserInfoDto.getMobilePhone();
        SmzyhdlReqVo smzyhdlReqVo = new SmzyhdlReqVo();
        smzyhdlReqVo.setYhm(authVo.getYhm());
        smzyhdlReqVo.setPassword(authVo.getPassword());
        SmzdlResponseVo.Body djyhmhmmdljk = sfjrApiService.djyhmhmmdljk(smzyhdlReqVo);
        //判断是否存在dj_org (mysql和oracle)
        SmzdlResponseVo.SsoLoginInfo ssoLoginInfo = djyhmhmmdljk.getSsoLoginInfo();
        SmzdlResponseVo.Smzxx smzxx = ssoLoginInfo.getSmzxx();
        List<SmzdlResponseVo.Nsr> nsrs = ssoLoginInfo.getNsrs();
        Set<String> djxhSet = new HashSet<>();
        for (SmzdlResponseVo.Nsr nsrVo : nsrs) {
            if ("N".equals(nsrVo.getTybz()) && (authVo.getNsrsbh().equals(nsrVo.getGsnsrsbh()) || authVo.getNsrsbh().equals(nsrVo.getShxydm()))) {
                //nsr = nsrVo;
                djxhSet.add(nsrVo.getGszdjxh());
            }
        }
        if (djxhSet.size() == 0) {
            throw new JeecgBootException("实名账号没有绑定该企业");
        }
        DjNsrxxPO djNsrxx = djNsrxxService.getByNsrsbhOrShxydm(authVo.getNsrsbh());
        //纳税人表信息 dj_nsrxx, dj_nsrzyxx
        if (djNsrxx == null) {
            //查询电局接口添加
            NsrxxCxResponseVo nsrxxCxResponseVo = null;
            for (String djxh : djxhSet) {
                NsrxxCxResponseVo nsrxxCxResponseVoTemp = sfjrApiService.nsrxxCx(djyhmhmmdljk.getSsoSessionId(), null, djxh);
                Nsrjbxx nsrjbxx = nsrxxCxResponseVoTemp.getNsrjbxx();
                //只保存满足条件的djxh对应的企业信息
                if ("N".equals(nsrjbxx.getKqccsztdjbz()) && Integer.valueOf(nsrjbxx.getKzztdjlxdm()) <= 1110 && "Y".equals(nsrjbxx.getYxbz())) {
                    nsrxxCxResponseVo = nsrxxCxResponseVoTemp;
                    break;
                }
            }
            Nsrjbxx nsrjbxx = nsrxxCxResponseVo.getNsrjbxx();
            String tynsrsbh = StringUtils.isNotBlank(nsrjbxx.getShxyDm()) ? nsrjbxx.getShxyDm() : nsrjbxx.getNsrsbh();
            DzswjBaseResponse<List<PzjgxxVo>> pzjgxxResponse = sfjrApiService.nsrxxPzjgxx(djyhmhmmdljk.getSsoSessionId(), nsrjbxx.getZgswjdm(), tynsrsbh);
            List<PzjgxxVo> pzjgxxVoList = pzjgxxResponse.getBody();
            djNsrxx = djNsrxxService.saveOrUpdateNsrjbxxAndPzjg(nsrxxCxResponseVo, pzjgxxVoList);
        }

        //存在则更新
        if (djOrg == null) {
            djOrg = new DjOrg();
            djOrg.setOrgId(djNsrxx.getTynsrsbh());
            djOrg.setDjxh(djNsrxx.getTynsrsbh());
            djOrg.setNsrsbh(djNsrxx.getNsrsbh());
            djOrg.setShxydm(djNsrxx.getShxydm());
            djOrg.setNsrmc(djNsrxx.getNsrmc());
        }
        //授权人手机号，授权人名称， 授权电局账号，授权电局名称
        djOrg.setRealYhm(authVo.getYhm());
        String encryptPw = null;
        try {
            encryptPw = DESUtil.encrypt(authVo.getPassword(), GuangdongSfjrApiService.DB_PASS_KEY);
        } catch (Exception e) {
            //日志
            throw new JeecgBootException("系统异常");
        }
        djOrg.setPassword(encryptPw);
        djOrg.setAutherMobile(mobile);
        if (smzxx != null) {
            djOrg.setAutherName(smzxx.getXm());
        }
        djOrg.setIsAuth(1);
        djOrgService.saveOrUpdate(djOrg);
        return Result.OK("授权成功");
    }


    @ThirdPartyApi(responseZip = true)
    @ApiOperation(value = "获取用户信息")
    @GetMapping("/getUserInfo")
    public Result<?> getUserInfo(@RequestParam String key) {
        String fullKey = RedisKeyConstant.AUTH_USER_KEY + key;
        String dataStr = redisUtil.getString(fullKey);
        if (StringUtils.isNotBlank(dataStr)) {
            redisUtil.setString(fullKey, dataStr, RedisKeyConstant.AUTH_USER_KEY_EXPIRE);
            AuthUserInfoDto authUserInfoDto = JSONObject.parseObject(dataStr, AuthUserInfoDto.class);
            if (authUserInfoDto != null) {
                return Result.OK(authUserInfoDto);
            }
        }
        return Result.noauth("登录信息已失效");
    }

    /**
     * 仅用于测试是否可以连通，直接返回OK
     * @return
     */
    @RequestMapping(value = "/testChannel", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<?> testChannel() {
        String agreement = "      <p style=\"text-align:center;margin: 30px auto\">\n" +
                "          <strong><span style=\"font-size: 20px;font-weight:800;\">企业财税信息授权书</span></strong>\n" +
                "      </p>\n" +
                "      <p style=\"text-indent: 2em;line-height: 22px\">\n" +
                "          <strong><span style=\"font-size:16px;font-weight:600;\">重要提示：为了维护您的合法权益，请在签署本授权书之前，仔细阅读本授权书各条款，关注您在授权书中的权利、义务。</span></strong>\n" +
                "      </p>\n" +
                "      <p style=\"margin-top:16px;margin-bottom:10px\">\n" +
                "          <span style=\"font-size: 21px\">&nbsp;</span>\n" +
                "      </p>\n" +
                "      <p style=\"margin-top:16px;margin-bottom:10px\">\n" +
                "          <strong><span style=\"font-size: 16px;font-weight:600;\">中国建设银行股份有限公司广东省分行：</span></strong>\n" +
                "      </p>\n" +
                "      <p style=\"margin-bottom:10px;line-height:22px;text-indent: 2em;text-align:justify;text-justify:inter-ideograph\">\n" +
                "          <span style=\"font-size: 16px\">1</span><span style=\"font-size: 16px\">.本公司承诺并确认在签署本授权书前，对自身提供的所有信息真实性、完整性、准确性承担全部责任。</span>\n" +
                "      </p>\n" +
                "      <p style=\"margin-bottom:10px;line-height:22px;text-indent: 2em;text-align:justify;text-justify:inter-ideograph\">\n" +
                "          <span style=\"font-size: 16px\">2.本公司同意并不可撤销地授权：贵行获取本公司在国家税务总局广东省电子税务局的财税信息，包括但不限于纳税人登记信息、纳税人税务申报信息、纳税人财务报</span><span style=\"font-size: 16px\">表信息、纳税人往来发票信息、纳税人税收处罚信息</span><span style=\"font-size: 16px\">等相关信息</span><span style=\"font-size: 16px\">。</span><span style=\"font-size: 16px\">上述财税信息仅用于本公司在贵行办理信贷业务及贷后监测管理使用。</span>\n" +
                "      </p>\n" +
                "      <p style=\"margin-bottom:10px;line-height:22px;text-indent: 2em\">\n" +
                "          <span style=\"font-size: 16px\">3.</span><span style=\"font-size: 16px\"><span style=\"\">本授权书自本公司有权操作人通过国家税务总局广东省电子税务局官网进入贵行</span>“区块链电子发票开通授权”，或通过贵行手机端“云易票”小程序开通授权，点击“本人已认真阅读并同意授权”及“确认企业信息”之日起立即生效，本授权书有效期至本公司与贵行业务关系终止之日或业务被贵行否决之日止。</span>\n" +
                "      </p>\n" +
                "      <p style=\"margin-bottom:10px;line-height:22px;text-indent: 2em\">\n" +
                "          <span style=\"font-size: 16px\">4.</span><span style=\"font-size: 16px\">本公司在本授权书生效期间因其他原因（包括不限于人为更改）导致提供的电子税务局实名账号或关联企业信息无法正常使用，应及时通知贵行，并向贵行重新提供与本公司有效关联的电子税务局实名账号进行身份核验确认。</span>\n" +
                "      </p>\n" +
                "      <p style=\"margin-bottom:10px;line-height:22px;text-indent: 2em\">\n" +
                "          <span style=\"font-size: 16px\">5.</span><span style=\"font-size: 16px\">授权书内容发生变化时，贵行需重新取得本公司授权。</span>\n" +
                "      </p>\n" +
                "      <p style=\"margin-bottom:10px;line-height:22px;text-indent: 2em\">\n" +
                "          <span style=\"font-size: 16px\">6.</span><span style=\"font-size: 16px\">贵行保留对本授权书及所有规则的最终解释权。</span>\n" +
                "      </p>\n" +
                "      <p style=\"text-indent: 2em;line-height: 125%\">\n" +
                "          <strong><span style=\"line-height:125%;font-size:19px\">&nbsp;</span></strong>\n" +
                "      </p>\n" +
                "      <p style=\"text-indent: 2em;line-height: 22px\">\n" +
                "          <strong><span style=\"line-height:22px;font-size:16px;font-weight:600;\">本公司声明：贵行已依法向本公司提示了企业财税信息授权的相关事项，应本公司要求对上述条款的概念、内容及法律效果做出了说明，本单位已知悉和理解。</span></strong>\n" +
                "      </p>\n" +
                "      <p>\n" +
                "          <span style=\"font-size:16px\">&nbsp;</span>\n" +
                "      </p>\n" +
                "      <p>\n" +
                "          <br/>\n" +
                "          <br/>\n" +
                "      </p>";
        return Result.OK(agreement);
    }
}
